
'''
Created on 2018年7月11日

@author: alive
'''
import base64

from Crypto import Random
from Crypto.Cipher import AES
import hashlib

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-s[-1]]


class AESCipher(object):

    def __init__( self, key):
        '''
        # 这里密钥key 长度必须为16（AES-128）,
        # 24（AES-192）,或者32 （AES-256）Bytes 长度
        '''
        self.key = key.encode('utf-8')

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw.encode('utf-8') ) ).decode('utf-8')

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))
    
if __name__ == "__main__":
    from hashlib import md5
    cipher = AESCipher('a933b6ab4911b9d1659ae4874da3956c')
    encrypted = cipher.encrypt('Secret Message A')
    decrypted = cipher.decrypt("gFi4xJ+vZ+JE0mTIkEszOaE4YwHE7A6sle+5vZMtmCCNlF9jrvN0EmOhV2JpNSBy9yCHB1ltEqrQ7iWqljuy4Zb3yuz5tYHGgSUtLXuMF4GS6EDBwM97+aI0Kz/5Uz4w")
    print(encrypted)
    print(decrypted)